<template>
  <div class="enhanced-ai-assistant">
    <div class="assistant-header">
      <div class="header-left">
        <el-icon class="ai-icon"><MagicStick /></el-icon>
        <h3>AI智能助手</h3>
        <el-tag type="success" size="small">在线</el-tag>
      </div>
      <div class="header-actions">
        <el-button size="small" text @click="showHistory = !showHistory">
          <el-icon><Clock /></el-icon>
          历史记录
        </el-button>
        <el-button size="small" text @click="clearConversation">
          <el-icon><Delete /></el-icon>
          清空对话
        </el-button>
        <el-button size="small" text @click="showSettings = !showSettings">
          <el-icon><Setting /></el-icon>
          设置
        </el-button>
      </div>
    </div>

    <div class="assistant-body">
      <!-- 侧边栏：历史记录或设置 -->
      <transition name="slide">
        <div v-if="showHistory || showSettings" class="assistant-sidebar">
          <!-- 历史记录 -->
          <div v-if="showHistory" class="history-panel">
            <h4>
              <el-icon><Clock /></el-icon>
              对话历史
            </h4>
            <div class="history-list">
              <div 
                v-for="session in conversationHistory" 
                :key="session.id"
                class="history-item"
                :class="{ active: session.id === currentSessionId }"
                @click="loadSession(session)"
              >
                <div class="history-title">{{ session.title }}</div>
                <div class="history-time">{{ formatTime(session.timestamp) }}</div>
              </div>
              <el-empty v-if="conversationHistory.length === 0" description="暂无历史记录" :image-size="60" />
            </div>
          </div>

          <!-- 设置面板 -->
          <div v-if="showSettings" class="settings-panel">
            <h4>
              <el-icon><Setting /></el-icon>
              AI设置
            </h4>
            <el-form label-width="100px" size="small">
              <el-form-item label="AI模型">
                <el-select v-model="settings.model">
                  <el-option label="GPT-4" value="gpt-4" />
                  <el-option label="GPT-3.5" value="gpt-3.5" />
                  <el-option label="Claude" value="claude" />
                </el-select>
              </el-form-item>
              <el-form-item label="创造性">
                <el-slider v-model="settings.temperature" :min="0" :max="1" :step="0.1" show-stops />
                <div class="slider-tips">
                  <span>保守</span>
                  <span>创新</span>
                </div>
              </el-form-item>
              <el-form-item label="响应长度">
                <el-slider v-model="settings.maxTokens" :min="500" :max="4000" :step="500" show-stops />
              </el-form-item>
              <el-form-item label="流式输出">
                <el-switch v-model="settings.streaming" />
              </el-form-item>
              <el-form-item label="上下文记忆">
                <el-switch v-model="settings.contextMemory" />
              </el-form-item>
              <el-form-item label="自动保存">
                <el-switch v-model="settings.autoSave" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </transition>

      <!-- 主对话区 -->
      <div class="chat-main">
        <!-- 上下文提示 -->
        <div v-if="contextInfo" class="context-banner">
          <el-icon><InfoFilled /></el-icon>
          <span>当前上下文：{{ contextInfo }}</span>
          <el-button size="small" text @click="clearContext">清除</el-button>
        </div>

        <!-- 消息列表 -->
        <div ref="messageListRef" class="message-list">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-icon">
              <el-icon><MagicStick /></el-icon>
            </div>
            <h3>你好！我是AI智能助手</h3>
            <p>我可以帮你快速创建表单、页面、流程等功能</p>
            
            <div class="quick-prompts">
              <h4>试试这些快捷指令：</h4>
              <div class="prompt-grid">
                <div 
                  v-for="prompt in quickPrompts" 
                  :key="prompt.text"
                  class="prompt-item"
                  @click="sendQuickPrompt(prompt.text)"
                >
                  <el-icon><component :is="prompt.icon" /></el-icon>
                  <span>{{ prompt.text }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 对话消息 -->
          <div 
            v-for="(message, index) in messages" 
            :key="index"
            class="message-item"
            :class="message.role"
          >
            <div class="message-avatar">
              <el-avatar v-if="message.role === 'user'" :size="36">
                <el-icon><User /></el-icon>
              </el-avatar>
              <el-avatar v-else :size="36" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><MagicStick /></el-icon>
              </el-avatar>
            </div>

            <div class="message-content">
              <div class="message-header">
                <span class="message-role">{{ message.role === 'user' ? '你' : 'AI助手' }}</span>
                <span class="message-time">{{ formatTime(message.timestamp) }}</span>
              </div>

              <div class="message-body">
                <!-- 流式输出 -->
                <div v-if="message.isStreaming" class="streaming-text">
                  {{ message.content }}
                  <span class="cursor-blink">▊</span>
                </div>
                <!-- 完整消息 -->
                <div v-else v-html="formatMessageContent(message.content)"></div>

                <!-- 代码块 -->
                <div v-if="message.code" class="code-block">
                  <div class="code-header">
                    <span>{{ message.codeLanguage || 'javascript' }}</span>
                    <el-button size="small" text @click="copyCode(message.code)">
                      <el-icon><DocumentCopy /></el-icon>
                      复制
                    </el-button>
                  </div>
                  <pre><code>{{ message.code }}</code></pre>
                </div>

                <!-- 操作按钮 -->
                <div v-if="message.actions && message.actions.length > 0" class="message-actions">
                  <el-button 
                    v-for="action in message.actions" 
                    :key="action.text"
                    size="small"
                    :type="action.type || 'primary'"
                    @click="handleAction(action)"
                  >
                    {{ action.text }}
                  </el-button>
                </div>
              </div>

              <!-- 消息反馈 -->
              <div v-if="message.role === 'assistant' && !message.isStreaming" class="message-feedback">
                <el-button size="small" text @click="copyMessage(message.content)">
                  <el-icon><DocumentCopy /></el-icon>
                </el-button>
                <el-button size="small" text @click="regenerateMessage(index)">
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
                <el-button size="small" text @click="thumbUp(message)">
                  <el-icon><Star /></el-icon>
                </el-button>
                <el-button size="small" text @click="thumbDown(message)">
                  <el-icon><WarningFilled /></el-icon>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 加载中 -->
          <div v-if="isThinking" class="thinking-indicator">
            <div class="thinking-avatar">
              <el-avatar :size="36" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><MagicStick /></el-icon>
              </el-avatar>
            </div>
            <div class="thinking-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-toolbar">
            <el-button size="small" text @click="attachFile">
              <el-icon><Paperclip /></el-icon>
              附件
            </el-button>
            <el-button size="small" text @click="insertTemplate">
              <el-icon><Document /></el-icon>
              模板
            </el-button>
            <el-button size="small" text @click="voiceInput">
              <el-icon><Microphone /></el-icon>
              语音
            </el-button>
          </div>

          <div class="input-box">
            <el-input
              v-model="inputText"
              type="textarea"
              :rows="3"
              :autosize="{ minRows: 3, maxRows: 6 }"
              placeholder="描述你的需求... (Shift+Enter换行，Enter发送)"
              @keydown.enter="handleEnterKey"
            />
          </div>

          <div class="input-actions">
            <div class="input-stats">
              {{ inputText.length }} / 2000
            </div>
            <el-button 
              type="primary" 
              :disabled="!inputText.trim() || isThinking"
              :loading="isThinking"
              @click="sendMessage"
            >
              <el-icon><Promotion /></el-icon>
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  MagicStick, Clock, Delete, Setting, User, InfoFilled,
  DocumentCopy, RefreshRight, Star, WarningFilled, Paperclip,
  Document, Microphone, Promotion, Edit, Share, Connection,
  Grid, TrendCharts
} from '@element-plus/icons-vue'

const props = defineProps({
  context: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['generate', 'action'])

// 状态
const showHistory = ref(false)
const showSettings = ref(false)
const isThinking = ref(false)
const inputText = ref('')
const messageListRef = ref(null)
const currentSessionId = ref(Date.now().toString())

// 消息列表
const messages = ref([])

// 上下文信息
const contextInfo = ref('')

// 对话历史
const conversationHistory = ref([])

// 设置
const settings = reactive({
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 2000,
  streaming: true,
  contextMemory: true,
  autoSave: true
})

// 快捷提示
const quickPrompts = [
  { text: '创建一个用户管理表单', icon: 'Edit' },
  { text: '设计一个CRUD列表页面', icon: 'Grid' },
  { text: '生成采购审批流程', icon: 'Share' },
  { text: '创建数据统计看板', icon: 'TrendCharts' }
]

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化消息内容
const formatMessageContent = (content) => {
  // 简单的Markdown渲染
  let formatted = content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
  
  return formatted
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim()) return
  
  const userMessage = {
    role: 'user',
    content: inputText.value,
    timestamp: Date.now()
  }
  
  messages.value.push(userMessage)
  
  const prompt = inputText.value
  inputText.value = ''
  
  // 滚动到底部
  scrollToBottom()
  
  // AI思考
  isThinking.value = true
  
  // 模拟AI响应
  setTimeout(() => {
    const assistantMessage = {
      role: 'assistant',
      content: '',
      timestamp: Date.now(),
      isStreaming: settings.streaming
    }
    
    messages.value.push(assistantMessage)
    isThinking.value = false
    
    if (settings.streaming) {
      // 流式输出
      streamResponse(assistantMessage, generateAIResponse(prompt))
    } else {
      // 直接输出
      assistantMessage.content = generateAIResponse(prompt)
      assistantMessage.isStreaming = false
    }
    
    scrollToBottom()
  }, 1000)
}

// 流式输出响应
const streamResponse = async (message, fullResponse) => {
  const words = fullResponse.split('')
  let currentIndex = 0
  
  const streamInterval = setInterval(() => {
    if (currentIndex < words.length) {
      message.content += words[currentIndex]
      currentIndex++
      scrollToBottom()
    } else {
      clearInterval(streamInterval)
      message.isStreaming = false
      
      // 如果是生成代码的请求，添加操作按钮
      if (fullResponse.includes('已生成') || fullResponse.includes('创建')) {
        message.actions = [
          { text: '应用到设计器', type: 'primary', action: 'apply' },
          { text: '查看代码', type: 'info', action: 'viewCode' }
        ]
      }
    }
  }, 30)
}

// 生成AI响应（模拟）
const generateAIResponse = (prompt) => {
  if (prompt.includes('表单')) {
    return '好的！我会为你创建一个**用户管理表单**。\n\n该表单包含以下字段：\n- 用户名（必填）\n- 邮箱（必填，邮箱格式验证）\n- 手机号（必填，手机号格式验证）\n- 部门（下拉选择）\n- 角色（多选）\n- 状态（开关）\n\n已生成表单配置，你可以直接应用到设计器中。'
  }
  
  if (prompt.includes('列表') || prompt.includes('CRUD')) {
    return '我会为你设计一个**CRUD列表页面**。\n\n功能包括：\n✓ 数据表格展示\n✓ 搜索筛选\n✓ 新增/编辑/删除\n✓ 批量操作\n✓ 导出功能\n✓ 分页\n\n已创建完整的CRUD页面配置。'
  }
  
  if (prompt.includes('流程')) {
    return '我会帮你生成一个**采购审批流程**。\n\n流程包含节点：\n1. 发起申请\n2. 部门主管审批\n3. 财务审核\n4. 总经理审批\n5. 采购执行\n6. 完成归档\n\n支持会签、或签、条件分支等高级功能。'
  }
  
  return '我理解了你的需求。让我为你生成相应的配置...'
}

// 快捷发送
const sendQuickPrompt = (text) => {
  inputText.value = text
  sendMessage()
}

// 处理Enter键
const handleEnterKey = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 复制消息
const copyMessage = (content) => {
  navigator.clipboard.writeText(content)
  ElMessage.success('已复制到剪贴板')
}

// 复制代码
const copyCode = (code) => {
  navigator.clipboard.writeText(code)
  ElMessage.success('代码已复制')
}

// 重新生成
const regenerateMessage = (index) => {
  ElMessage.info('重新生成中...')
}

// 点赞/点踩
const thumbUp = (message) => {
  ElMessage.success('感谢你的反馈')
}

const thumbDown = (message) => {
  ElMessage.info('我们会努力改进')
}

// 处理操作
const handleAction = (action) => {
  emit('action', action)
  ElMessage.success(`执行操作：${action.text}`)
}

// 清空对话
const clearConversation = () => {
  messages.value = []
  ElMessage.success('对话已清空')
}

// 清除上下文
const clearContext = () => {
  contextInfo.value = ''
}

// 其他功能
const attachFile = () => {
  ElMessage.info('附件功能开发中')
}

const insertTemplate = () => {
  ElMessage.info('模板功能开发中')
}

const voiceInput = () => {
  ElMessage.info('语音输入功能开发中')
}

const loadSession = (session) => {
  ElMessage.success(`加载会话：${session.title}`)
}

// 监听context变化
watch(() => props.context, (newContext) => {
  if (newContext && Object.keys(newContext).length > 0) {
    contextInfo.value = `${newContext.type} - ${newContext.name}`
  }
}, { deep: true, immediate: true })
</script>

<style scoped>
.enhanced-ai-assistant {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.assistant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.ai-icon {
  font-size: 24px;
  color: #667eea;
}

.header-left h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 5px;
}

.assistant-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 侧边栏 */
.assistant-sidebar {
  width: 280px;
  border-right: 1px solid #e4e7ed;
  background: #f5f7fa;
  overflow-y: auto;
}

.history-panel,
.settings-panel {
  padding: 20px;
}

.history-panel h4,
.settings-panel h4 {
  margin: 0 0 15px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  padding: 12px;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.history-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.history-item.active {
  background: #ecf5ff;
  border-left: 3px solid #409eff;
}

.history-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.slider-tips {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 主对话区 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.context-banner {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 20px;
  background: #ecf5ff;
  border-bottom: 1px solid #b3d8ff;
  color: #409eff;
  font-size: 14px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

/* 欢迎消息 */
.welcome-message {
  text-align: center;
  padding: 40px 20px;
}

.welcome-icon {
  font-size: 64px;
  color: #667eea;
  margin-bottom: 20px;
}

.welcome-message h3 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
}

.welcome-message p {
  margin: 0 0 30px 0;
  color: #909399;
  font-size: 16px;
}

.quick-prompts h4 {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
}

.prompt-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  max-width: 600px;
  margin: 0 auto;
}

.prompt-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: #f5f7fa;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  color: #606266;
}

.prompt-item:hover {
  border-color: #409eff;
  background: #ecf5ff;
  color: #409eff;
  transform: translateY(-2px);
}

/* 消息项 */
.message-item {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.message-role {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.message-time {
  font-size: 12px;
  color: #c0c4cc;
}

.message-body {
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

.message-item.assistant .message-body {
  background: white;
  border: 1px solid #e4e7ed;
}

.streaming-text {
  display: inline;
}

.cursor-blink {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.code-block {
  margin-top: 10px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 12px;
  color: #909399;
}

.code-block pre {
  margin: 0;
  padding: 12px;
  background: #282c34;
  overflow-x: auto;
}

.code-block code {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  color: #abb2bf;
}

.message-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.message-feedback {
  display: flex;
  gap: 5px;
  margin-top: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.message-item:hover .message-feedback {
  opacity: 1;
}

/* 思考指示器 */
.thinking-indicator {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.thinking-dots {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 16px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.thinking-dots span {
  width: 8px;
  height: 8px;
  background: #409eff;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 输入区域 */
.input-area {
  border-top: 1px solid #e4e7ed;
  background: white;
}

.input-toolbar {
  display: flex;
  gap: 5px;
  padding: 10px 20px;
  border-bottom: 1px solid #f5f7fa;
}

.input-box {
  padding: 15px 20px 0;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px 15px;
}

.input-stats {
  font-size: 12px;
  color: #c0c4cc;
}

/* 滑动动画 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s;
}

.slide-enter-from {
  transform: translateX(-100%);
}

.slide-leave-to {
  transform: translateX(-100%);
}

/* 滚动条 */
.message-list::-webkit-scrollbar,
.assistant-sidebar::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-thumb,
.assistant-sidebar::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover,
.assistant-sidebar::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>

